<template>
  <div class="job-create">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button type="text" @click="handleBack" class="back-btn">
          <el-icon>
            <ArrowLeft />
          </el-icon>
          返回
        </el-button>
        <div class="header-content">
          <h1 class="page-title">{{ isEdit ? '编辑职位' : '发布职位' }}</h1>
          <p class="page-desc">{{ isEdit ? '修改职位信息' : '创建新的招聘职位' }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-button @click="handleSaveDraft" :loading="savingDraft">
          <el-icon>
            <Document />
          </el-icon>
          保存草稿
        </el-button>
        <el-button type="primary" @click="handlePublish" :loading="publishing">
          <el-icon>
            <Upload />
          </el-icon>
          {{ isEdit ? '更新并发布' : '发布职位' }}
        </el-button>
      </div>
    </div>

    <!-- 职位表单 -->
    <el-form ref="jobFormRef" :model="jobForm" :rules="jobRules" label-width="120px" class="job-form">
      <!-- 基本信息卡片 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <el-icon>
              <InfoFilled />
            </el-icon>
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="职位名称" prop="title">
              <el-input v-model="jobForm.title" placeholder="请输入职位名称" maxlength="50" show-word-limit clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="所属部门" prop="department">
              <el-select v-model="jobForm.department" placeholder="请选择部门" filterable allow-create style="width: 100%">
                <el-option v-for="dept in departmentOptions" :key="dept.value" :label="dept.label"
                  :value="dept.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="工作地点" prop="location">
              <el-select v-model="jobForm.location" placeholder="请选择工作地点" filterable allow-create style="width: 100%">
                <el-option v-for="location in locationOptions" :key="location.value" :label="location.label"
                  :value="location.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="工作类型" prop="employmentType">
              <el-select v-model="jobForm.employmentType" placeholder="请选择工作类型" style="width: 100%">
                <el-option label="全职" value="full_time" />
                <el-option label="兼职" value="part_time" />
                <el-option label="实习" value="intern" />
                <el-option label="合同工" value="contract" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="经验要求" prop="seniority">
              <el-select v-model="jobForm.seniority" placeholder="请选择经验要求" style="width: 100%">
                <el-option label="初级" value="junior" />
                <el-option label="中级" value="mid" />
                <el-option label="高级" value="senior" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="学历要求" prop="education">
              <el-select v-model="jobForm.education" placeholder="请选择学历要求" style="width: 100%">
                <el-option label="不限" value="none" />
                <el-option label="本科" value="bachelor" />
                <el-option label="硕士" value="master" />
                <el-option label="博士" value="phd" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 薪资福利卡片 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <el-icon>
              <Money />
            </el-icon>
            <span>薪资福利</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :xs="24" :md="8">
            <el-form-item label="最低薪资" prop="salaryMin">
              <el-input-number v-model="jobForm.salaryMin" :min="0" :max="999999" :step="1000" placeholder="最低薪资"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="8">
            <el-form-item label="最高薪资" prop="salaryMax">
              <el-input-number v-model="jobForm.salaryMax" :min="0" :max="999999" :step="1000" placeholder="最高薪资"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="8">
            <el-form-item label="货币类型" prop="currency">
              <el-select v-model="jobForm.currency" placeholder="请选择货币" style="width: 100%">
                <el-option label="人民币 (CNY)" value="CNY" />
                <el-option label="美元 (USD)" value="USD" />
                <el-option label="欧元 (EUR)" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="福利待遇">
          <el-input v-model="jobForm.benefits" type="textarea" :rows="3" placeholder="请描述福利待遇，如五险一金、年终奖、带薪年假等"
            maxlength="500" show-word-limit />
        </el-form-item>
      </el-card>

      <!-- 职位详情卡片 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <el-icon>
              <Document />
            </el-icon>
            <span>职位详情</span>
          </div>
        </template>

        <el-form-item label="职位描述" prop="description">
          <el-input v-model="jobForm.description" type="textarea" :rows="4" placeholder="请详细描述职位的工作内容、发展前景等"
            maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="岗位职责" prop="responsibilities">
          <el-input v-model="jobForm.responsibilities" type="textarea" :rows="4" placeholder="请列出主要的岗位职责和工作内容"
            maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="任职要求" prop="requirements">
          <el-input v-model="jobForm.requirements" type="textarea" :rows="4" placeholder="请列出技能要求、工作经验等任职要求"
            maxlength="1000" show-word-limit />
        </el-form-item>

        <el-form-item label="职位标签">
          <div class="tags-input">
            <el-tag v-for="tag in jobForm.tagList" :key="tag" closable @close="handleRemoveTag(tag)" class="tag-item">
              {{ tag }}
            </el-tag>
            <el-input v-if="tagInputVisible" ref="tagInputRef" v-model="tagInputValue" size="small" style="width: 100px"
              @keyup.enter="handleAddTag" @blur="handleAddTag" />
            <el-button v-else size="small" @click="showTagInput" class="add-tag-btn">
              <el-icon>
                <Plus />
              </el-icon>
              添加标签
            </el-button>
          </div>
          <div class="form-tip">
            添加相关技能标签，如：Java、Spring Boot、Vue等
          </div>
        </el-form-item>
      </el-card>

      <!-- 其他设置卡片 -->
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <el-icon>
              <Setting />
            </el-icon>
            <span>其他设置</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item label="职位负责人" prop="ownerId">
              <el-select v-model="jobForm.ownerId" placeholder="请选择负责人" filterable style="width: 100%">
                <el-option v-for="user in hrUsers" :key="user.id" :label="user.name" :value="user.id">
                  <div class="user-option">
                    <el-avatar :size="24" :src="user.avatar">
                      <el-icon>
                        <User />
                      </el-icon>
                    </el-avatar>
                    <span class="user-name">{{ user.name }}</span>
                    <span class="user-role">{{ user.roleName }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="发布状态">
              <el-radio-group v-model="publishStatus">
                <el-radio label="draft">保存为草稿</el-radio>
                <el-radio label="publish">立即发布</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Document,
  Upload,
  InfoFilled,
  Money,
  Setting,
  Plus,
  User
} from '@element-plus/icons-vue'
import usePageState from './hooks/usePageState'

const {
  route,
  router,
  jobFormRef,
  tagInputRef,
  savingDraft,
  publishing,
  tagInputVisible,
  tagInputValue,
  publishStatus,
  isEdit,
  jobForm,
  jobRules,
  departmentOptions,
  locationOptions,
  hrUsers
} = usePageState();


// 事件处理函数
/**
 * 返回上一页
 */
const handleBack = () => {
  router.back()
}

/**
 * 保存草稿
 */
const handleSaveDraft = async () => {
  try {
    savingDraft.value = true

    // 基本验证（不包括必填项）
    if (!jobForm.title.trim()) {
      ElMessage.warning('请至少填写职位名称')
      return
    }

    // TODO: 调用保存草稿API
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('草稿保存成功')
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存失败')
  } finally {
    savingDraft.value = false
  }
}

/**
 * 发布职位
 */
const handlePublish = async () => {
  try {
    // 表单验证
    await jobFormRef.value.validate()

    publishing.value = true

    // 构建提交数据
    const submitData = {
      ...jobForm,
      tags: jobForm.tagList.join(','),
      status: publishStatus.value === 'publish' ? 'open' : 'draft'
    }
    console.log('提交数据:', submitData)

    // TODO: 调用发布API
    await new Promise(resolve => setTimeout(resolve, 1500))

    const action = isEdit.value ? '更新' : '发布'
    ElMessage.success(`职位${action}成功`)

    // 跳转到职位列表
    router.push('/enterprise/jobs')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    publishing.value = false
  }
}

/**
 * 显示标签输入框
 */
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

/**
 * 添加标签
 */
const handleAddTag = () => {
  const tag = tagInputValue.value.trim()
  if (tag && !jobForm.tagList.includes(tag)) {
    if (jobForm.tagList.length >= 10) {
      ElMessage.warning('最多只能添加10个标签')
      return
    }
    jobForm.tagList.push(tag)
  }

  tagInputVisible.value = false
  tagInputValue.value = ''
}

/**
 * 移除标签
 */
const handleRemoveTag = (tag: string) => {
  const index = jobForm.tagList.indexOf(tag)
  if (index > -1) {
    jobForm.tagList.splice(index, 1)
  }
}

/**
 * 加载职位数据（编辑模式）
 */
const loadJobData = async () => {
  if (!isEdit.value) return

  try {
    // TODO: 调用API获取职位详情
    const jobData = {
      title: 'Java高级开发工程师',
      department: '技术部',
      location: '北京',
      employmentType: 'full_time',
      seniority: 'senior',
      education: 'bachelor',
      salaryMin: 20000,
      salaryMax: 35000,
      currency: 'CNY',
      description: '负责公司核心业务系统的开发和维护...',
      requirements: '1. 本科及以上学历，计算机相关专业...',
      responsibilities: '1. 参与系统架构设计和技术选型...',
      benefits: '五险一金、年终奖、带薪年假、弹性工作制',
      tagList: ['Java', 'Spring Boot', '微服务'],
      ownerId: 1
    }

    Object.assign(jobForm, jobData)
  } catch (error) {
    console.error('加载职位数据失败:', error)
    ElMessage.error('加载职位数据失败')
  }
}

// 生命周期
onMounted(() => {
  loadJobData()
  console.log("route", route);
})

onUnmounted(() => {

})
</script>

<style scoped>
.job-create {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.back-btn {
  margin-top: 4px;
  color: #409eff;
}

.header-content {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.page-desc {
  color: #909399;
  margin: 0;
}

.header-right {
  display: flex;
  gap: 12px;
}

.job-form {
  max-width: 1200px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.add-tag-btn {
  border-style: dashed;
  color: #409eff;
  background: #f0f9ff;
  border-color: #409eff;
}

.add-tag-btn:hover {
  background: #409eff;
  color: white;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.user-option {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.user-name {
  flex: 1;
  font-weight: 500;
}

.user-role {
  font-size: 12px;
  color: #909399;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }

  .header-left {
    width: 100%;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
  }

  .job-form {
    max-width: none;
  }
}
</style>
